"use strict";
cc._RF.push(module, 'e0468MnAs5KE5iwX7W9nRn1', 'game');
// script/game.js

"use strict";

cc.Class({
  "extends": cc.Component,
  properties: {
    mapNode: cc.Node // foo: {
    //     // ATTRIBUTES:
    //     default: null,        // The default value will be used only when the component attaching
    //                           // to a node for the first time
    //     type: cc.SpriteFrame, // optional, default is typeof default
    //     serializable: true,   // optional, default is true
    // },
    // bar: {
    //     get () {
    //         return this._bar;
    //     },
    //     set (value) {
    //         this._bar = value;
    //     }
    // },

  },
  // LIFE-CYCLE CALLBACKS:
  onLoad: function onLoad() {
    this.tt = 0;
    this.enemyAmount = 3;
    this.enemyPrefab = null;
    cc.director.getPhysicsManager().enabled = true; // 开启碰撞

    cc.director.getCollisionManager().enabled = true;
    cc.director.getCollisionManager().enabledDebugDraw = true; // cc.director.getPhysicsManager().enabled = true
    // cc.director.getPhysicsManager().debugDrawFlags = true;

    this.initMapNode(this.mapNode); // this.createEnemy()
  },
  start: function start() {},
  initMapNode: function initMapNode(mapNode) {
    var tiledMap = mapNode.getComponent(cc.TiledMap);
    var tiledSize = tiledMap.getTileSize();
    var layer = tiledMap.getLayer('wall');
    var layerSize = layer.getLayerSize();

    for (var i = 0; i < layerSize.width; i++) {
      for (var j = 0; j < layerSize.height; j++) {
        var tiled = layer.getTiledTileAt(i, j, true);

        if (tiled.gid != 0) {
          tiled.node.group = 'wall';
          var body = tiled.node.addComponent(cc.RigidBody);
          body.type = cc.RigidBodyType.Static;
          var collider = tiled.node.addComponent(cc.PhysicsBoxCollider);
          collider.offset = cc.v2(tiledSize.width / 2, tiledSize.height / 2);
          collider.size = tiledSize;
          collider.apply();
        }
      }
    }
  },
  // update (dt) {
  //     this.tt += dt
  //     if(this.tt > 1) {
  //         this.createEnemy()
  //         this.tt = 0
  //     }
  // },
  randomRange: function randomRange(min, max) {
    return Math.random() * (max - min) + min;
  },
  createEnemy: function createEnemy() {
    // 获取当前敌人数量
    var noeds = this.node.children;
    var enemyNodes = noeds.filter(function (e) {
      return e.name == 'enemy';
    }); // console.log('enemyNodes',enemyNodes )
    // 控制生成三个怪

    if (enemyNodes.length < this.enemyAmount) {
      // 补齐敌人
      var amount = this.enemyAmount - enemyNodes.length;

      for (var i = 0; i < amount; i++) {
        // 复制一个节点进行生成
        var enemy = cc.instantiate(enemyNodes[0]); // 随机坐标

        enemy.setPosition(cc.v2(this.randomRange(-150, 150), this.randomRange(-34, 170)));
        this.node.addChild(enemy);
      }
    }
  }
});

cc._RF.pop();